package top.gytf.unifiedcall.example.springmvc.controller;

import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.ReflectUtil;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import top.gytf.unifiedcall.common.support.UnifiedCallApi;
import top.gytf.unifiedcall.example.springmvc.constant.M001Exception;

@RestController
@RequestMapping("/producer-test")
public class ProducerTestController {
    @GetMapping("/without-wrap")
    @UnifiedCallApi(customizedResponse = true)
    public String withoutWrap(@RequestParam("message") String message) {
        return "Server[without-wrap]: " + message;
    }

    @UnifiedCallApi(
            since = @UnifiedCallApi.Version(major = 0, minor = 5, patch = 0),
            until = @UnifiedCallApi.Version(major = 1, minor = 9, patch = 4)
    )
    @GetMapping("/say")
    public String say(@RequestParam("message") String message) {
        return "Server: " + message;
    }

    @GetMapping("/throw")
    public String throwException(@RequestParam("message") String message) {
        throw new M001Exception(message);
    }

    @GetMapping("/toggleException")
    @UnifiedCallApi(
            since = @UnifiedCallApi.Version(major = 1, minor = 0, patch = 0),
            until = @UnifiedCallApi.Version(major = 1, minor = 2, patch = 0)
    )
    public String toggleException(
            @RequestParam("clsName") String clsName,
            @Nullable @RequestParam(value = "message", required = false) String message) throws Throwable {
        Class<Object> cls = ClassUtil.loadClass(clsName);
        if (Throwable.class.isAssignableFrom(cls)) {
            if (message != null) {
                throw (Throwable) ReflectUtil.newInstance(cls, message);
            } else {
                throw (Throwable) ReflectUtil.newInstance(cls);
            }
        }
        return cls + " is not a throwable class";
    }
}
